import axios from 'axios';
import { message } from 'antd';
import type { RequestConfig, ResponseData } from './types';
import { RequestCache } from './cache';
import { RequestCancel } from './cancel';
import { LoadingService } from '@/components/GlobalLoading';

// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  timeoutErrorMessage: '请求超时，请稍后再试',
});

// 创建缓存和取消请求实例
const cache = new RequestCache();
const cancelRequest = new RequestCancel();

// 全局loading计数器
let loadingCount = 0;

/**
 * 显示loading
 */
const showLoading = () => {
  if (loadingCount === 0) {
    LoadingService.show();
  }
  loadingCount++;
};

/**
 * 隐藏loading
 */
const hideLoading = () => {
  loadingCount--;
  if (loadingCount === 0) {
    LoadingService.hide();
  }
};

// 请求拦截器
instance.interceptors.request.use(
  (config: RequestConfig) => {
    // 处理取消重复请求
    cancelRequest.addPending(config);

    // 处理缓存
    if (config.enableCache) {
      const cacheKey = cache.generateKey(config);
      const cacheData = cache.get(cacheKey);
      if (cacheData) {
        return Promise.reject({
          config,
          code: 'CACHE_HIT',
          data: cacheData,
        });
      }
    }

    // 显示loading
    if (config.showLoading !== false) {
      showLoading();
    }

    // 设置token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const config = response.config as RequestConfig;

    // 移除请求队列
    cancelRequest.removePending(config);

    // 隐藏loading
    if (config.showLoading !== false) {
      hideLoading();
    }

    // 处理缓存
    if (config.enableCache) {
      const cacheKey = cache.generateKey(config);
      cache.set(cacheKey, response.data, config.cacheTimeout || 5 * 60 * 1000);
    }

    const { code, message: msg, data } = response.data as ResponseData;

    // 处理业务状态码
    if (code === 200) {
      return data;
    } else {
      message.error(msg || '请求失败');
      return Promise.reject(response.data);
    }
  },
  (error) => {
    // 处理缓存命中
    if (error.code === 'CACHE_HIT') {
      return error.data;
    }

    const config = error.config as RequestConfig;

    // 移除请求队列
    cancelRequest.removePending(config);

    // 隐藏loading
    if (config?.showLoading !== false) {
      hideLoading();
    }

    // 处理取消请求
    if (axios.isCancel(error)) {
      return Promise.reject('请求被取消');
    }

    // 显示错误信息
    message.error(error.message || '请求失败');
    return Promise.reject(error);
  },
);

export default instance;
